<?php
class cmsdream_main {
	public $db;
	public $config;
	public $setting = FALSE;
	public $public_query_vars = array(
			'p',
			'page_id',
			'year',
			'monthnum',
			'category_name',
			'tag',
			'day',
			'attachment',
			'paged',
			'cat',
			'pagename',
			'name',
			'attachment_id',
			's',
			'author',
			'author_name',
			'feed'
		);
	public $permanent_page_name = array('twitter','archives','verify-code','set-client','boot','comments');
	public $query_vars;
	public $request;
	public $hash = '';
	public $logged_user;
	
	public $query;
	public $cache;
	
	public function url_encode($str) {
		return str_replace('+', '%20', urlencode($str));
	}
	
	public function get($key, $default = NULL) {
		if(isset($this->query_vars[$key]))
			return $this->query_vars[$key];
		else
			return $default;
	}
	
	public function url($c, $key = null, $reqs = null) {
		if($c=='home') {
			return $this->config->ABSURL ? $this->setting->home : $this->config->SITEPATH;
		}
		return $this->cache->url($c, $key, $reqs);
	}
	
	public function referer($def=NULL){
		$ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
		$ref = $ref == '' ? (empty($def) ? $this->get('home').'/' : $def) : $ref;
		return $ref;
	}
	
	public function get_page_params($name=null) {
		$pn = $this->get('pagename');
		$p = explode('/', $pn);
		$rst = array();
		$base = $p[0];
		$key = $p[0];
		
		if(count($p) > 1) {
			array_shift($p);
			foreach($p as $k => $v) {
				if($k % 2 ==0) {
					if(isset($p[$k + 1])) {
						$rst[$p[$k]] = $p[$k + 1];
					} else {
						$key = $p[$k];
					}
				}
			}
		}
		if($base==$key) $key = null;
		if($name===null) return $base;
		$rst['param'] = $key;
		if(is_array($name)) return $rst;
		return isset($rst[$name]) ? $rst[$name] : null;
	}
	
	public function merge_tag_font_size($tags) {
		$largest = 22; $smallest = 8;
		
		$counts = array();
		$real_counts = array();
		foreach ( (array) $tags as $key => $tag ) {
			$real_counts[ $key ] = $tag->count;
			$counts[ $key ] = ($tag->count + $smallest) * $smallest;
		}

		$min_count = min( $counts );
		$spread = max( $counts ) - $min_count;
		if ( $spread <= 0 )
			$spread = 1;
		$font_spread = $largest - $smallest;
		if ( $font_spread < 0 )
			$font_spread = 1;
		$font_step = $font_spread / $spread;

		$arr = array();
		foreach ( $tags as $key => $tag ) {
			$arr[$key] = new stdClass;
			$arr[$key] = $tag;
			$arr[$key]->size = round($smallest + ( ( $counts[ $key ] - $min_count ) * $font_step ), 2);
		}
		return $arr;
	}
	
	public function check_post_password($pid = 0){
		if(!isset($_SESSION['post_password'])) return false;
		$pwds = $_SESSION['post_password'];
		if(!empty($pwds) && is_array($pwds)) {
			return isset($pwds[$pid]);
		}
		return false;
	}
	
	public function get_paged_link(){
		$link = $this->config->ABSURL ? $this->setting->home : '';
		$link .= $this->config->SITEPATH . '/';
		if(preg_match('/^(.*)page\/([\d]+)$/i', $this->request)){
			$link .= preg_replace('/^(.*)page\/([\d]+)$/i', '$1page/%page%', $this->request);
		} else {
			$link .= ($this->request == '') ? 'page/%page%' : $this->request . '/page/%page%';
		}
		return $link;
	}
	
	public function wapPagedContent($content, $limit = 1000, $ilen = 500, $blen = 100) {
		$content = preg_replace('/<a[^>]+href=(\'|")([^\'"]+)(\'|")[^>]+><img[^>]+src=(\'|")([^\'"]+)(\'|")[^>]+><\/a>/i', '[img src="$5" link="$2"]'."\n", $content);
		$content = preg_replace('/<img[^>]+src=(\'|")([^\'"]+)(\'|")[^>]+>/i', '[img src="$2"]', $content);
		$content = preg_replace('/<object[^>]+>(.*)<\/object>/i', "[OBJECT]\n", $content);
		$content = preg_replace('/<strong>/i', "[STRONG]", $content);
		$content = preg_replace('/<\/strong>/i', "[/STRONG]", $content);
		$content = strip_tags($content);
		
		$line = explode("\n", $content);
		
		$cs = array();
		$key = 0;
		$str = "";
		foreach($line AS $c) {
			if(trim($c) != '') {
				$len = $this->getStringLength($str);
				if(preg_match_all('/\[STRONG\]/i', $c, $ss)) {
					foreach($ss[0] as $m){
						$len = $len - strlen($m);
					}
				}
				if(preg_match_all('/\[STRONG\]/i', $c, $ss)) {
					foreach($ss[0] as $m){
						$len = $len - strlen($m);
					}
				}
				if(preg_match_all('/\[img[^\]]+\]/i', $c, $ss)) {
					foreach($ss[0] as $m){
						$len = $len - strlen($m);
						$len = $len + $ilen;
					}
				}
				$c = preg_replace('/\[img[\s]+src="([^"]+)"[\s]+link="([^"]+)"\]/i', '<a href="$2"><img src="$1" /></a><br/>', $c);
				$c = preg_replace('/\[img[\s]+src="([^"]+)"\]/i', '<img src="$1" /><br/>', $c);
				$c = preg_replace('/\[STRONG\]/i', "<strong>", $c);
				$c = preg_replace('/\[\/STRONG\]/i', "</strong>", $c);
				$br = $this->getStringLength($c) > $blen ? "<br/>" : "";
				$str .= $c . "<br/>$br\n";
				if($len >= $limit) {
					$cs[$key] = preg_replace('/(<br\/>){1,}$/i', '', $str);
					$str = "";
					$key++;
				}
			}
		}
		$cs[$key] = preg_replace('/(<br\/>){1,}$/i', '', $str);
		return $cs;
	}
	
	public function wapSubString($content, $maxlen = 100, $suffixStr = " ...") {
		$content = $this->htmlSubString($content, $maxlen, $suffixStr);
		$content = preg_replace("/<img[^>]+>/i", "[PHOTO]", $content);
		$content = preg_replace("/<object[^>]+>(.*)<\/object>/i", "[OBJECT]", $content);
		$content = strip_tags($content);
		$content = preg_replace("/[\n\s]+/i", " ", $content);
		$content = preg_replace('/(\[PHOTO\]){2,}/i', '[ALBUM]', $content);
		return $content;
	}
	
	public function htmlSubString($content, $maxlen = 480, $suffixStr = " ..."){
		//把字符按HTML标签变成数组。
		$content = preg_split("/(<[^>]+?>)/si",$content, -1,PREG_SPLIT_NO_EMPTY| PREG_SPLIT_DELIM_CAPTURE);
		$wordrows=0; //中英字数
		$outstr="";  //生成的字串
		$wordend=false; //是否符合最大的长度
		$beginTags=0; //除<img><br><hr>这些短标签外，其它计算开始标签，如<div*>
		$endTags=0;  //计算结尾标签，如</div>，如果$beginTags==$endTags表示标签数目相对称，可以退出循环。
		//print_r($content);
		foreach($content as $value){
			if (trim($value)=="") continue; //如果该值为空，则继续下一个值
			if (strpos(";$value","<")>0){
				//如果与要载取的标签相同，则到处结束截取。
				if (trim($value)==$maxlen) {
					$wordend=true;
					continue;
				}
				if ($wordend==false){
					$outstr.=$value;
					if (!preg_match("/<img([^>]+?)>/is",$value) && !preg_match("/<param([^>]+?)>/is",$value) && !preg_match("/<!([^>]+?)>/is",$value) && !preg_match("/<br([^>]+?)>/is",$value) && !preg_match("/<hr([^>]+?)>/is",$value)) {
						$beginTags++; //除img,br,hr外的标签都加1
					}
				}else if (preg_match("/<\/([^>]+?)>/is",$value,$matches)){
					$endTags++;
					$outstr.=$value;
					if ($beginTags==$endTags && $wordend==true) break; //字已载完了，并且标签数相称，就可以退出循环。
				}else{
					if (!preg_match("/<img([^>]+?)>/is",$value) && !preg_match("/<param([^>]+?)>/is",$value) && !preg_match("/<!([^>]+?)>/is",$value) && !preg_match("/<br([^>]+?)>/is",$value) && !preg_match("/<hr([^>]+?)>/is",$value)) {
						$beginTags++; //除img,br,hr外的标签都加1
						$outstr.=$value;
					}
				}
			}else{
				if (is_numeric($maxlen)){ //截取字数
					$curLength=$this->getStringLength($value);
					$maxLength=$curLength+$wordrows;
					if ($wordend==false){
						if ($maxLength>$maxlen){ //总字数大于要截取的字数，要在该行要截取
							$outstr.=$this->subString($value,0,$maxlen-$wordrows) . $suffixStr;
							$wordend=true;
						}else{
							$wordrows=$maxLength;
							$outstr.=$value;
						}
					}
				}else{
					if ($wordend==false) $outstr.=$value;
				}
			}
		}
		//循环替换掉多余的标签，如<p></p>这一类
		while(preg_match("/<([^\/][^>]*?)><\/([^>]+?)>/is",$outstr)){
			$outstr = preg_replace_callback("/<([^\/][^>]*?)><\/([^>]+?)>/is",create_function(
							'$matches',
							'
								$arr_tags1=explode(" ",$matches[1]);
								if ($arr_tags1[0]==$matches[2]){
									return "";
								}else{
									$matches[0]=str_replace("<","[html_&lt;]",$matches[0]);
									$matches[0]=str_replace(">","[html_&gt;]",$matches[0]);
									return $matches[0];
								}
							'
						),$outstr);
		}
		//把误换的标签换回来
		if (strpos(";".$outstr,"[html_")>0){
			$outstr=str_replace("[html_&lt;]","<",$outstr);
			$outstr=str_replace("[html_&gt;]",">",$outstr);
		}
		//echo htmlspecialchars($outstr);	
		return $outstr;
	}
	
	private function getStringLength($text){
		if (function_exists('mb_substr')) {
			$length=mb_strlen($text,'UTF-8');
		} elseif (function_exists('iconv_substr')) {
			$length=iconv_strlen($text,'UTF-8');
		} else {
			preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar);
			$length=count($ar[0]);
		}
		return $length;
	}

	private function subString($text, $start=0, $limit=12) {
		if (function_exists('mb_substr')) {
			$more = (mb_strlen($text,'UTF-8') > $limit) ? TRUE : FALSE;
			$text = mb_substr($text, 0, $limit, 'UTF-8');
			return $text;
		} elseif (function_exists('iconv_substr')) {
			$more = (iconv_strlen($text,'UTF-8') > $limit) ? TRUE : FALSE;
			$text = iconv_substr($text, 0, $limit, 'UTF-8');
			//return array($text, $more);
			return $text;
		} else {
			preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar);
			if(func_num_args() >= 3) {
				if (count($ar[0])>$limit) {
					$more = TRUE;
					$text = join("",array_slice($ar[0],0,$limit));
				} else {
					$more = FALSE;
					$text = join("",array_slice($ar[0],0,$limit));
				}
			} else {
				$more = FALSE;
				$text =  join("",array_slice($ar[0],0));
			}
			return $text;
		}
	}
	
	public function __construct() {
		
	}
	
	public function __destruct(){
	
	}
	
}

